/**
 *   ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 *　　┃　　　┃神兽保佑
 *　　┃　　　┃代码无BUG！
 *　　┃　　　┗━━━┓
 *　　┃　　　　　　　┣┓
 *　    ┃　　　　　　　┏┛
 *　　┗┓┓┏━┳┓┏┛
 *　　　┃┫┫　┃┫┫
 *　　　┗┻┛　┗┻┛
**/
package com.asd.common.Filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.asd.common.utils.Info;
import com.asd.common.utils.PropKit;

/**
 * 路由拦截器
 *
 * @author zhanqi
 * @date 2020年03月05日
 */
@WebFilter(filterName = "filterRoutes", urlPatterns = "/*", initParams = {
		@WebInitParam(name = "filterRoutes", value = "路由拦截器") }, dispatcherTypes = { DispatcherType.REQUEST })
public class FilterRoutes implements Filter {
	@Override
	public void destroy() {
		/* 在 Filter 实例被 Web 容器从服务移除之前调用 */
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		synchronized (FilterRoutes.class) {
			String sPath = request.getServletPath();
			action(sPath, request, response);
		}
	}

	private void action(String sPath, HttpServletRequest request, ServletResponse response)
			throws IOException, ServletException {
		String routes = null,action=null;
		// vue代理打包后
		if (PropKit.getBoolean("removeApi", false)) {
			String vueApiName = PropKit.get("vueApiName", "/api/");
			if (sPath.startsWith(vueApiName)) {
				sPath = sPath.substring(vueApiName.length() - 1);
			}
		}
		int beginIndex = sPath.lastIndexOf("/");
		if (beginIndex>0) {
			 routes = sPath.substring(0, beginIndex);
			 action = sPath.substring(beginIndex + 1);
			 action=action==null?"index":action;
		}else if(beginIndex==0) {
			routes = "/";
			action=sPath.equals("/")?"index":sPath;
		}
		request.setAttribute("methodName",action);
		request.getRequestDispatcher(routes).forward(request, response);

	}

	@Override
	public void init(FilterConfig config) {
		// 获取初始化参数
		String site = config.getInitParameter("filterRoutes");
		Info.out(getClass(), site);
	}

}
